package x.ovo.wechat.bot.plugin;

import picocli.CommandLine;
import x.ovo.wechat.bot.core.command.CommandExcutor;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@CommandLine.Command(name = "emoticon", description = "表情包发送")
public class EmoticonExecutor extends CommandExcutor {


    public EmoticonExecutor(Plugin plugin) {
        super(plugin);
    }

    @CommandLine.Command(name = "add", description = "添加表情及触发关键词")
    public String add(@CommandLine.Parameters(paramLabel = "name", index = "0", description = "表情包名称") String name,
                      @CommandLine.Parameters(paramLabel = "md5", index = "1", split = ",", description = "表情包md5") List<String> md5,
                      @CommandLine.Parameters(paramLabel = "keywords", index = "2", split = ",", description = "触发关键词") List<String> keywords) {
        Map<String, Object> map = Map.of("name", name, "md5", md5, "keywords", keywords);
        List<Map<String, Object>> data = this.plugin.<List<Map<String, Object>>>getConfig().computeIfAbsent("data", k -> new ArrayList<>());
        data.add(map);
        this.plugin.saveConfig();
        return "添加成功";
    }

    @CommandLine.Command(name = "remove", description = "移除表情及触发关键词")
    public String remove(@CommandLine.Parameters(paramLabel = "name", index = "0", description = "表情包名称") String name) {
        List<Map<String, Serializable>> data = this.plugin.<List<Map<String, Serializable>>>getConfig().get("data");
        if (Objects.isNull(data)) return "暂无数据";
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).get("name").equals(name)) {
                data.remove(i);
                this.plugin.saveConfig();
                return "移除成功";
            }
        }
        return null;
    }

    @CommandLine.Command(name = "list", description = "列出所有表情包")
    public String list() {
        List<Map<String, Serializable>> data = this.plugin.<List<Map<String, Serializable>>>getConfig().get("data");
        if (data == null) return "暂无数据";
        StringBuilder builder = new StringBuilder();
        for (Map<String, Serializable> item : data) {
            builder.append(item.get("name")).append(" ").append(List.of(item.get("keywords"))).append("\n");
        }
        return builder.toString();
    }

    @CommandLine.Command(name = "black", description = "添加关键词黑名单")
    public String black(@CommandLine.Parameters(paramLabel = "keyword", index = "0", split = ",", description = "关键词") String[] keyword) {
        this.plugin.<List<String>>getConfig().computeIfAbsent("blacklist", k -> new ArrayList<>()).addAll(List.of(keyword));
        this.plugin.saveConfig();
        return "添加成功";
    }
}